package com.sicau.smart_farmer.config.database;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.convert.CustomConversions;
import org.springframework.data.mapping.model.CamelCaseSplittingFieldNamingStrategy;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;

/**
 * @author sxt
 * @create 2019-11-22 23:36
 */
@Configuration
@Slf4j
public class MongoConfig {

    @Bean
    public MappingMongoConverter setMapping(MongoDbFactory mongoDbFactory, MongoMappingContext mappingContext, BeanFactory beanFactory){
        log.info("setting to ignore '_class' field");

        DefaultDbRefResolver defaultDbRefResolver = new DefaultDbRefResolver(mongoDbFactory);
        MappingMongoConverter mappingMongoConverter = new MappingMongoConverter(defaultDbRefResolver, mappingContext);

        mappingMongoConverter.setCustomConversions(beanFactory.getBean(CustomConversions.class));

        mappingMongoConverter.setTypeMapper(new DefaultMongoTypeMapper(null));

//        mappingContext.setFieldNamingStrategy(new UpperCaseWithUnderscoreFieldNamingStrategy());
        mappingContext.setFieldNamingStrategy(new CamelCaseSplittingFieldNamingStrategy("_"));

        return mappingMongoConverter;
    }
}
